import time

from tornado import web, ioloop


# 知识点：
# 1. url的各种配置
# 2. url命名，配合reverse_url来使用
# 3. 给handler传入初始值


class MainHandler(web.RequestHandler):

    # 当客户端发起不同的http方法的时候，只需要重载handler中对应的方法即可
    async def get(self, *args, **kwargs):
        self.write("hello world 3!")


class SleepHandler(web.RequestHandler):

    async def get(self, *args, **kwargs):
        # 在编写中不能在里面写同步IO逻辑
        time.sleep(2)
        self.write("sleep")


class PostIdHandler(web.RequestHandler):

    async def get(self, id, *args, **kwargs):
        href = self.reverse_url("post_name", "zhangsan")  # 生成一个跳转的连接
        self.redirect(href)  # 跳转
        # self.write("ID is {} -> {}".format(id, href))


class PostNameHandler(web.RequestHandler):

    def initialize(self, name):
        self.db_name = name

    async def get(self, name, *args, **kwargs):
        self.write("Name is {},db_name:{}".format(name, self.db_name))


class PostInfoHandler(web.RequestHandler):

    async def get(self, name, age, gender, *args, **kwargs):
        self.write("姓名：{}，年龄：{}，性别：{}".format(name, age, gender))


db = {
    'name': "test"
}

urls = [
    ("/", MainHandler),
    web.URLSpec("/sleep/?", SleepHandler, name="sleep"),

    web.URLSpec("/post/(\d+)/?", PostIdHandler, name="post_id"),  # /post/1
    web.URLSpec("/post/(\w+)/?", PostNameHandler, db, name="post_name"),  # /post/name
    # web.URLSpec("/post/(\w+)/(\d+)/(\w+)/?", PostInfoHandler, name="post_info"),  # /post/name/age/gender
    web.URLSpec("/post/(?P<name>\w+)/(?P<age>\d+)/(?P<gender>\w+)/?", PostInfoHandler, name="post_info"),
    # /post/name/age/gender
]

if __name__ == '__main__':
    app = web.Application(urls, debug=True)

    app.listen(8000)

    ioloop.IOLoop.current().start()
